import {t} from 'i18next';

export function getSignalLevel<T extends object>(
  signalValue: number,
  signalStrengthMap: T,
): T[keyof T] {
  // 找到最接近的小于等于 signalValue 的 key
  const matchedKey = Object.keys(signalStrengthMap)
    .map(Number)
    .filter(key => key <= signalValue)
    .sort((a, b) => b - a)[0]; // 降序取最大值
  return signalStrengthMap[matchedKey as keyof T];
}

export function formatMinutesToTimeUnit(minutes: number): string {
  if (minutes < 60) {
    return `${minutes}` + t('workplace.minute');
  }

  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;

  if (hours < 24) {
    if (remainingMinutes === 0) {
      return `${hours}${t('sys.app.hour')}`;
    }
    return (
      `${hours}${t('sys.app.hour')}${remainingMinutes}` + t('workplace.minute')
    );
  }

  const days = Math.floor(hours / 24);
  const remainingHours = hours % 24;

  if (remainingHours === 0) {
    return `${days}` + t('common.app.day');
  }

  return (
    `${days + t('common.app.day')}${remainingHours}` + t('workplace.minute')
  );
}

export function RGBAtoHex(rgba: string): string {
  const match = rgba.match(
    /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/,
  );
  if (!match) {
    return rgba;
  }
  const r = parseInt(match[1], 10).toString(16).padStart(2, '0');
  const g = parseInt(match[2], 10).toString(16).padStart(2, '0');
  const b = parseInt(match[3], 10).toString(16).padStart(2, '0');
  return `#${r}${g}${b}`;
}

/**
 * 为十六进制颜色添加透明度
 * @param hexColor 十六进制颜色值，如 "#FF891F" 或 "#F81"
 * @param opacity 透明度值，范围 0-1
 * @returns 带透明度的十六进制颜色值，如 "#FF891F80"
 */
export function hexWithOpacity(hexColor: string, opacity: number): string {
  // 确保透明度在有效范围内
  const alpha = Math.max(0, Math.min(1, opacity));

  // 移除可能的 # 前缀
  let hex = hexColor.replace('#', '');

  // 处理简写形式 (如 #F81 -> #FF8811)
  if (hex.length === 3) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  }

  // 将透明度转换为十六进制
  const alphaHex = Math.round(alpha * 255)
    .toString(16)
    .padStart(2, '0');

  // 返回带透明度的十六进制颜色
  return `#${hex}${alphaHex}`;
}
type CancelableRequest<TParams extends any[], TResult> = (
  ...args: TParams
) => Promise<TResult>;

export function withCancelable<TParams extends any[], TResult>(
  requestFn: (signal: AbortSignal, ...args: TParams) => Promise<TResult>,
): CancelableRequest<TParams, TResult> {
  let controller: AbortController | null = null;

  return async (...args: TParams): Promise<TResult> => {
    if (controller) {
      controller.abort();
    }

    controller = new AbortController();
    const signal = controller.signal;
    return await requestFn(signal, ...args);
  };
}
